<template>
  <div class='app-container'>
    <div class='button-container'>
      <el-button class='filter-item' type='primary' @click='openEditRolesDialog(null,true)' icon='edit'>新增岗位</el-button>
    </div>
    <div>
      <!-- 表格 -->
      <el-table ref="RoleTable" @selection-change="onSelectionChanged" :data="GridPageList"
                v-loading.body="gridDataIsLoading"
                element-loading-text="数据加载中..." border fit highlight-current-row>

        <el-table-column align="center" label='序号' width="150">
          <template scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>

        <el-table-column label="岗位名称" width="200">
          <template scope="scope">
            {{scope.row.rolename}}
          </template>
        </el-table-column>

        <el-table-column label="岗位说明" width="200">
          <template scope="scope">
            {{scope.row.roledesc}}
          </template>
        </el-table-column>


        <el-table-column label="授权" width="450">
          <template scope="scope">
            <template v-for="route in scope.row.routes">
              <el-tag
                type='primary' close-transition>{{route.name}}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template scope="scope">
            <el-button icon="edit" size="small" type="primary" @click=openEditRolesDialog(scope.row,false)>编辑岗位
            </el-button>
            <el-button icon="setting" size="small" @click=openSetRoleRoutesDialog(scope.row)>设置权限</el-button>
            <el-button icon="delete" type="danger" size="small" @click="deleteRole(scope.$index, scope.row)">删除岗位
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div v-show="!gridDataIsLoading" class="pagination-container">
      <el-pagination @size-change="onPageSizeChanged" @current-change="onPageNoChanged"
                     :current-page.sync="paginationConfig.currentQueryPage"
                     :page-sizes="[10,20,30, 50]" :page-size="paginationConfig.selectedPageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="dataCount">
      </el-pagination>
    </div>
    <!-- 新增岗位 -->
    <el-dialog title='新增岗位' :visible.sync='createRoleDialogOpend'>
      <el-form :model="editingRole" ref="RoleForm" :rules="rules">
        <el-form-item label='岗位名称' prop="rolename">
          <el-input v-model='editingRole.rolename' placeholder="请输入岗位名称"></el-input>
        </el-form-item>
        <el-form-item label='岗位说明' prop="roledesc">
          <el-input v-model='editingRole.roledesc' placeholder="请输入岗位说明"></el-input>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleEditRoleSubmit'>确定</el-button>
        <el-button @click='createRoleDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>


    <!-- 指定路由 -->
    <el-dialog title='指定路由' :visible.sync='roleRoutesDialogOpend'>
      <div class="role-transfer">
        <el-transfer v-model="selectdRotes"
                     :titles="['未选岗位', '已选岗位']"
                     :props="{ key: 'path', label: 'name'}"
                     :data="allRoutes"></el-transfer>
      </div>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleSetRoleRoutesSubmit'>确定</el-button>
        <el-button @click='roleRoutesDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'roleset',
    data() {
      return {
        gridDataSource: [],
        // 当前分页数据开始index
        startIndex: 0,
        // 当前分页数据结束index
        endIndex: 0,
        currentSelectedRow: null,
        gridDataIsLoading: false,
        selectdRotes: [],
        allRoutes: [],
        paginationConfig: {selectedPageSize: 10, currentQueryPage: 0},
        roleRoutesDialogOpend: false,
        createRoleDialogOpend: false,
        editingRole: {
          roleid: 0,
          rolename: '',
          roledesc: ''
        },
        rules: {
          rolename: [
            {required: true, trigger: 'blur', message: '岗位名必填'},
            {type: 'string', max: 20, trigger: 'blur', message: '岗位名称必须小于20个字'}
          ],
          roledesc: [
            {type: 'string', max: 200, trigger: 'blur', message: '岗位说明必须小于200个字'}
          ]
        }
      };
    },
    methods: {
      /**
       * 刷新数据
       */
      refreshData() {
        this.gridDataIsLoading = true;
        let getRotes = this.$http.get('/Oss/Auth/GetAllRoute?allRoute=false').then((response) => {
          if (response.data.isSuccess) {
            this.allRoutes = response.data.routes;
          }
        });

        let getRoles = this.$http.get('/Oss/Auth/GetAllRoles').then((response) => {
          if (response.data.isSuccess) {
            this.gridDataSource = response.data.roles;
            this.paginationConfig.currentQueryPage = 1;
          }
          this.paginationConfig.currentQueryPage = 0;
        });

        this.$http.all([getRoles, getRotes]).then(() => {
          this.gridDataIsLoading = false;
        }).catch(() => {
          this.gridDataIsLoading = false;
        });
      },
      computeDataIndex(pageNo, pageSize) {
        this.startIndex = pageSize * (pageNo - 1) + 1;
        this.endIndex = this.startIndex + pageSize;
        console.log(this.startIndex);
        console.log(this.endIndex);
      },

      openEditRolesDialog(row, isnew) {
        console.log(row);
        if (isnew) {
          this.editingRole = {
            roleid: 0,
            rolename: '',
            roledesc: ''
          };
        } else {
          this.editingRole = {
            roleid: row.roleid,
            rolename: row.rolename,
            roledesc: row.roledesc
          };
        }
        this.createRoleDialogOpend = true;
      },

      /**
       * 分页变化
       */
      onPageSizeChanged(size) {
        this.paginationConfig.selectedPageSize = size;
        this.computeDataIndex(this.paginationConfig.currentQueryPage, size);
      },
      onPageNoChanged(page) {
        this.paginationConfig.currentQueryPage = page;
        this.computeDataIndex(page, this.paginationConfig.selectedPageSize);
      },
      /**
       * 表格selectchanged
       */
      onSelectionChanged(select) {
        this.currentSelectedRow = select;
      },
      openSetRoleRoutesDialog(row) {
        this.currentSelectedRow = row;

        /**
         * 初始化已选择
         */
        this.selectdRotes.splice(0, this.selectdRotes.length);
        if (row.routes) {
          row.routes.forEach(x => {
            this.selectdRotes.push(x.path);
          });
        }
        this.roleRoutesDialogOpend = true;
      },

      /**
       * 绑定岗位路由
       */
      handleSetRoleRoutesSubmit() {
        let roleid = this.currentSelectedRow.roleid;
        this.$http.post('/Oss/Auth/SetRoleRoutes', {
          roleid: roleid,
          routepaths: this.selectdRotes
        }).then((response) => {
          if (response.data.isSuccess) {
            this.$message({
              message: '指定路由成功!',
              type: 'success'
            });
            this.roleRoutesDialogOpend = false;
          }
        }).then(() => {
          this.$http.get('/Oss/Auth/GetRoleInfo', {
            params: {
              roleid: roleid
            }
          }).then((response) => {
            if (response.data.isSuccess) {
              let updateIndex = this.gridDataSource.findIndex((role) => {
                return role.roleid === roleid;
              });

              this.gridDataSource.splice(updateIndex, 1, response.data.role);
            }
          });
        }).catch(() => {
          this.$message({
            message: '数据保存失败!',
            type: 'error'
          });
        });
      },
      /**
       * 提交新增岗位表单
       */
      handleEditRoleSubmit() {
        this.$refs.RoleForm.validate((valid) => {
          if (valid) {
            this.$http.post('/Oss/Auth/SaveRole', {
              roleid: this.editingRole.roleid,
              rolename: this.editingRole.rolename,
              roledesc: this.editingRole.roledesc
            }).then((response) => {
              if (response.data.isSuccess) {
                this.$message({
                  message: '新增成功!',
                  type: 'success'
                });
                if (response.data) {
                  console.log(response.data.role.roleid);
                  let updateIndex = this.gridDataSource.findIndex((role) => {
                    return role.roleid === response.data.role.roleid;
                  });
                  if (updateIndex > 0) {
                    this.gridDataSource.splice(updateIndex, 1, response.data.role);
                  } else {
                    this.gridDataSource.push(response.data.role);
                  }
                }
                this.createRoleDialogOpend = false;
              } else {
                this.$message({
                  message: '数据提交出现错误,请稍后重试!',
                  type: 'error'
                });
              }
            }).catch(() => {
              this.$message({
                message: '数据提交出现错误,请稍后重试!',
                type: 'error'
              });
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 删除岗位
       */
      deleteRole(index, row) {
        let Roleid = row.roleid;
        if (Roleid && Roleid > 0) {
          this.$confirm('删除岗位后相关用户将不会在拥有该岗位的权限, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              this.$http.delete('/Oss/Auth/DeleteRole', {
                params: {
                  roleid: Roleid
                }
              }).then((response) => {
                if (response.data.isSuccess) {
                  this.gridDataSource.splice(index, 1);
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                }
              });
            }
          );
        }
      }
    },
    created() {
      this.refreshData();
    },
    computed: {
      GridPageList() {
        if (this.gridDataSource && this.gridDataSource.length > 0) {
          if (this.startIndex > 0 && this.endIndex > 0) {
            return this.gridDataSource.slice(this.startIndex - 1, this.endIndex - 1);
          } else {
            return [];
          }
        } else {
          return [];
        }
      },
      dataCount() {
        if (this.gridDataSource) {
          return this.gridDataSource.length;
        } else {
          return 0;
        }
      }
    }
  };
</script>
<style rel="stylesheet/scss" lang="scss">
  .role-transfer {
    display: inline-flex;
    position: relative;
    justify-content: center;
    align-items: center;
    width: 100%;

  }
</style>
